package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.bean.JingYingBean;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.RegisterRolePirVO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddJingYingActivity extends BaseActivity implements View.OnClickListener {
    private EditText entname;//单位名称
    private  AddJingYingActivity activity=this;
    private EditText prname;//单位负责人

    private EditText prtel;//联系方式

    private Spinner enttype;//单位类型

    private EditText operation;//经营范围

    private EditText encode;//证件编码

    private EditText spissnum;//两化编码

    private EditText address;//单位地址

    private Spinner mainenttype;//单位分类
    private Spinner status;//状态
    private Button save;

    private Button cancle;
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private CustomApplication application;
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(AddJingYingActivity.this, JingYingActivity.class);

                    startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_jing_ying);
        init();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void init() {
        entname = (EditText) findViewById(R.id.entname);
        prname = (EditText) findViewById(R.id.prname);
        prtel = (EditText) findViewById(R.id.prtel);
        enttype = (Spinner) findViewById(R.id.enttype);
        operation = (EditText) findViewById(R.id.operation);
        encode = (EditText) findViewById(R.id.encode);
        spissnum = (EditText) findViewById(R.id.spissnum);
        address = (EditText) findViewById(R.id.address);
        mainenttype = (Spinner) findViewById(R.id.mainenttype);
        status = (Spinner) findViewById(R.id.status);
        save = (Button) findViewById(R.id.save);
        cancle = (Button) findViewById(R.id.cancle);
        application = (CustomApplication) getApplication();
        initData();
        save.setOnClickListener(this);
        cancle.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save:
                if ("".equals(entname.getText().toString().trim()) || "".equals(prname.getText().toString().trim())
                        || "".equals(prtel.getText().toString().trim()) || "".equals(((RegisterRolePirVO) enttype.getSelectedItem()).getId())
                        || "".equals(operation.getText().toString().trim()) || "".equals(encode.getText().toString().trim())
                        //|| "".equals(spissnum.getText().toString().trim()) || "".equals(address.getText().toString().trim())
                        || "".equals(((RegisterRolePirVO) mainenttype.getSelectedItem()).getId())
                        || "".equals(((RegisterRolePirVO) status.getSelectedItem()).getId())) {
                    Toast.makeText(getApplicationContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
                } else {
                    final Map<String, String> map = new HashMap<String, String>();
                    map.put("entname", entname.getText().toString().trim());
                    map.put("prname", prname.getText().toString().trim());
                    map.put("prtel", prtel.getText().toString().trim());
                    map.put("enttype", ((RegisterRolePirVO) enttype.getSelectedItem()).getId());
                    map.put("operation", operation.getText().toString().trim());
                    map.put("encode", encode.getText().toString().trim());
                    map.put("spissnum", spissnum.getText().toString().trim());
                    map.put("address", address.getText().toString().trim());
                    map.put("mainenttype", ((RegisterRolePirVO) mainenttype.getSelectedItem()).getId());
                    map.put("status", ((RegisterRolePirVO) status.getSelectedItem()).getId());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                OkHttpClient client = new OkHttpClient();
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, String> m : map.entrySet()) {
                                    builder.add(m.getKey(), m.getValue());
                                }
                                RequestBody resultRequestBody = builder.build();
                                Request enttypeRequest = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doAdd/c_aj_jydw").post(resultRequestBody).build();
                                Response enttyperesponse = client.newCall(enttypeRequest).execute();
                                if(enttyperesponse.isSuccessful()){
                                    String result = enttyperesponse.body().string();
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    System.out.println(resultMap);
                                    if ((boolean) resultMap.get("success")) {

                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);


                                    } else {
                                        Message message = new Message();
                                        message.what = 0;
                                        handler.sendMessage(message);
                                    }
                                }
                            }catch (Exception e){
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
                break;
            case R.id.cancle:
                finish();
                break;
        }
    }

    public void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    //生产单位分类
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/comboJson/c_aj_jydw-mainenttype?userId=" + String.valueOf(application.getLoginUser().getLogin_id())).build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        final List<RegisterRolePirVO> types = gson.fromJson(result, new TypeToken<List<RegisterRolePirVO>>() {
                        }.getType());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ArrayAdapter<RegisterRolePirVO> aradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, types);
                                aradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                mainenttype.setAdapter(aradapter);
                                mainenttype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                                        ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
                                        ((TextView) parent.getChildAt(0)).setTextSize(18);
                                        RegisterRolePirVO item = (RegisterRolePirVO) mainenttype.getSelectedItem();
                                        final String mainenttypeId = (String) item.getId();
                                        if (mainenttypeId != null && !"".equals(mainenttypeId)) {
                                            //生产单位分类
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        OkHttpClient client = new OkHttpClient();
                                                        RequestBody enttypeRequestBody = new FormBody.Builder()
                                                                .add("exp", "select tid ID, tname CN from dt_dwtype where tlevel=3 and ptid =" + mainenttypeId)
                                                                .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                                                                .build();
                                                        Request enttypeRequest = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/comboJson").post(enttypeRequestBody).build();
                                                        Response enttyperesponse = client.newCall(enttypeRequest).execute();
                                                        if (enttyperesponse.isSuccessful()) {//成功
                                                            String result = enttyperesponse.body().string();
                                                            final List<RegisterRolePirVO> enttypereses = gson.fromJson(result, new TypeToken<List<RegisterRolePirVO>>() {
                                                            }.getType());
                                                            System.out.println(enttypereses);
                                                            runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    ArrayAdapter<RegisterRolePirVO> enttyperesaradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, enttypereses);
                                                                    enttyperesaradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                                                    enttype.setAdapter(enttyperesaradapter);
                                                                    enttype.setOnItemSelectedListener(OnCatSpinnerCL);
                                                                }
                                                            });
                                                        }
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            }).start();
                                        }
                                    }

                                    public void onNothingSelected(AdapterView<?> parent) {
                                    }
                                });
                            }
                        });
                    }
                    //状态
                    Request statusRequest = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/comboJson/c_aj_jydw-status?userId=" + String.valueOf(application.getLoginUser().getLogin_id())).build();
                    Response statusResponse = client.newCall(statusRequest).execute();
                    if (response.isSuccessful()) {//成功
                        String result = statusResponse.body().string();
                        final List<RegisterRolePirVO> statuses = gson.fromJson(result, new TypeToken<List<RegisterRolePirVO>>() {
                        }.getType());
                        // System.out.println(types);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ArrayAdapter<RegisterRolePirVO> statusaradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, statuses);
                                statusaradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                status.setAdapter(statusaradapter);
                                status.setOnItemSelectedListener(OnCatSpinnerCL);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("AddJingYing Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2.connect();
        AppIndex.AppIndexApi.start(client2, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client2, getIndexApiAction());
        client2.disconnect();
    }
}
